package com.example.coursedesign.dao;

import com.example.coursedesign.entity.User;
import com.example.coursedesign.utils.JDBCUtils;
import android.util.Log;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class UserDao {

    private static final String TAG = "mysql-as_coursedesign-UserDao";

    /**
     * function: 登录
     */
    public int login(String account, String password) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int msg = 0;

        try {
            connection = JDBCUtils.getConn();
            if (connection != null) {
                String sql = "SELECT * FROM user WHERE account = ?";
                ps = connection.prepareStatement(sql);
                ps.setString(1, account);
                rs = ps.executeQuery();

                if (rs.next()) {
                    String dbPassword = rs.getString("password");
                    if (password.equals(dbPassword)) {
                        msg = 1; // 密码正确
                    } else {
                        msg = 2; // 密码错误
                    }
                } else {
                    Log.e(TAG, "查询结果为空");
                    msg = 3; // 用户不存在
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d(TAG, "异常login：" + e.getMessage());
            msg = 0; // 数据库操作失败
        } finally {
           // JDBCUtils.closeConnection(connection, ps, rs);
        }

        return msg;
    }

    /**
     * function: 注册
     */
    public boolean register(User user) {
        Connection connection = null;
        PreparedStatement ps = null;

        try {
            connection = JDBCUtils.getConn();
            if (connection != null) {
                String sql = "INSERT INTO user (account, name, password, gender, avatar, phone) VALUES (?, ?, ?, ?, ?, ?)";
                ps = connection.prepareStatement(sql);

                ps.setString(1, user.getAccount());
                ps.setString(2, user.getName());
                ps.setString(3, user.getPassword());
                ps.setString(4, user.getGender());
                ps.setString(5, user.getAvatar());
                ps.setString(6, user.getPhone());

                int rowsAffected = ps.executeUpdate();
                return rowsAffected > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(TAG, "异常register：" + e.getMessage());
        } finally {
        //    JDBCUtils.closeConnection(connection, ps, null);
        }

        return false;
    }

    public boolean updateUserPartially(User user, Map<String, String> changedFields) {
        if (user == null) {
            return false;
        }

        // 应用更改到用户对象
        for (Map.Entry<String, String> entry : changedFields.entrySet()) {
            switch (entry.getKey()) {
                case "name":
                    user.setName(entry.getValue());
                    break;
                case "gender":
                    user.setGender(entry.getValue());
                    break;
                case "avatar":
                    user.setAvatar(entry.getValue());
                    break;
                case "phone":
                    user.setPhone(entry.getValue());
                    break;
                default:
                    break;
            }
        }

        // 使用固定的账号信息进行更新
        return updateUser(user);
    }

    /**
     * 更新固定账号的用户信息
     *
     * @param user 需要更新的用户对象
     * @return 更新是否成功
     */
    public boolean updateUser(User user) {
        final String FIXED_ACCOUNT = "user123"; // 替换为实际的固定账号

        Connection connection = null;
        PreparedStatement ps = null;

        try {
            connection = JDBCUtils.getConn();
            if (connection != null) {
                String sql = "UPDATE user SET name = ?, password = ?, gender = ?, avatar = ?, phone = ? WHERE account = ?";
                ps = connection.prepareStatement(sql);

                ps.setString(1, user.getName());
                ps.setString(2, user.getPassword());
                ps.setString(3, user.getGender());
                ps.setString(4, user.getAvatar());
                ps.setString(5, user.getPhone());
                ps.setString(6, FIXED_ACCOUNT); // 使用固定的账号

                int rowsAffected = ps.executeUpdate();
                return rowsAffected > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(TAG, "异常updateFixedAccountUser：" + e.getMessage());
        } finally {
           // JDBCUtils.closeConnection(connection, ps, null);
        }

        return false; // 如果发生异常或没有数据被更新，则返回false
    }

    /**
     * function: 根据账号进行查找该用户是否存在
     */
    public User findUser(String account) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;

        try {
            connection = JDBCUtils.getConn();
            if (connection != null) {
                String sql = "SELECT * FROM user WHERE account = ?";
                ps = connection.prepareStatement(sql);
                ps.setString(1, account);
                rs = ps.executeQuery();

                if (rs.next()) {
                    user = new User(
                            rs.getInt("id"),
                            rs.getString("account"),
                            rs.getString("name"),
                            rs.getString("password"),
                            rs.getString("gender"),
                            rs.getString("role"),
                            rs.getString("avatar"),
                            rs.getString("phone"),
                            null,
                            null,
                            null,
                            null
                    );
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d(TAG, "异常findUser：" + e.getMessage());
        } finally {
            //JDBCUtils.closeConnection(connection, ps, rs);
        }

        return user;
    }

    public User findUserByAccount(String account) {
        account = "user123";
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;

        try {
            connection = JDBCUtils.getConn();
            if (connection != null) {
                Log.d(TAG, "Database connection successful");

                String sql = "SELECT * FROM user WHERE account = ?";
                ps = connection.prepareStatement(sql);
                ps.setString(1, account);
                Log.d(TAG, "Executing query: " + sql + " with account: " + account);

                rs = ps.executeQuery();

                if (rs.next()) {
                    Log.d(TAG, "User found in database");
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setName(rs.getString("name"));
                    user.setPassword(rs.getString("password"));
                    user.setGender(rs.getString("gender"));
                    user.setRole(rs.getString("role"));
                    user.setAvatar(rs.getString("avatar"));
                    user.setPhone(rs.getString("phone"));
                    user.setAccount(rs.getString("account"));

                    Log.d(TAG, "User details: " + user.toString());
                } else {
                    Log.d(TAG, "No user found for account: " + account);
                }
            } else {
                Log.e(TAG, "Failed to establish database connection");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(TAG, "Exception in findUserByAccount: " + e.getMessage());
        } finally {
            //JDBCUtils.closeConnection(connection, ps, rs);
        }

        return user;
    }
}